package com.cungmua.app.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.base.Joiner;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by kelvin.nguyen on 6/17/14.
 */
public class Cart implements Serializable {
    private List<CartItem> items;

    public Cart() {
        items = new ArrayList<CartItem>();
    }

    public List<CartItem> getItems() {
        return items;
    }

    public void setItems(List<CartItem> items) {
        this.items = items;
    }

    @JsonIgnore
    public int getTotalQuantity() {
        int result = 0;
        for (CartItem item : items) {
            result += item.getQuantity();
        }
        return result;
    }
    public List<Integer> getGroups() {
        List<Integer> groups = new ArrayList<Integer>();
        for (CartItem item : items) {
            if (groups.indexOf(item.getProductId()) < 0)
                groups.add(item.getProductId());
        }

        return groups;
    }

    public List<CartItem> itemsByGroup(int groupId) {
        List<CartItem> groupItems = new ArrayList<CartItem>();

        for (CartItem item : items) {
            if (item.getProductId() == groupId)
                groupItems.add(item);
        }
        return groupItems;
    }

    @Override
    public String toString() {
        List<Integer> groups = getGroups();

        List<String> groupString = new ArrayList<String>();
        for (int i : groups) {
            List<CartItem> groupItems = itemsByGroup(i);
            String str = i + "=" + Joiner.on(",").join(groupItems);
            groupString.add(str);
        }
        return Joiner.on("|").join(groupString);
    }
}
